/**
 * CollectionTaskTable Component
 * 采集任务列表表格组件
 * Features: 状态标签、进度显示、实时更新、操作按钮
 */

import React from 'react'
import { Table, Tag, Button, Space, Tooltip, Progress } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { EyeOutlined, PauseCircleOutlined, RedoOutlined, PlayCircleOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import type { CollectionTask } from '@/services/models/types'
import { TaskStatus, TaskType } from '@/services/models/types'

interface CollectionTaskTableProps {
  tasks: CollectionTask[]
  loading?: boolean
  onCancel?: (id: number) => void
  onStart?: (id: number) => void
  onRetry?: (id: number) => void
}

/**
 * 任务状态标签映射
 */
const STATUS_TAG_CONFIG: Record<TaskStatus, { color: string; text: string }> = {
  [TaskStatus.PENDING]: { color: 'default', text: '等待中' },
  [TaskStatus.RUNNING]: { color: 'processing', text: '运行中' },
  [TaskStatus.SUCCESS]: { color: 'success', text: '成功' },
  [TaskStatus.FAILED]: { color: 'error', text: '失败' },
  [TaskStatus.CANCELLED]: { color: 'default', text: '已取消' },
  [TaskStatus.PARTIAL_SUCCESS]: { color: 'warning', text: '部分成功' },
}

/**
 * 采集类型标签映射
 */
const COLLECTION_TYPE_CONFIG: Record<TaskType, { color: string; text: string }> = {
  [TaskType.FULL]: { color: 'blue', text: '全量' },
  [TaskType.INCREMENTAL]: { color: 'cyan', text: '增量' },
}

export const CollectionTaskTable: React.FC<CollectionTaskTableProps> = ({
  tasks,
  loading = false,
  onStart,
  onCancel,
  onRetry,
}) => {
  const navigate = useNavigate()

  /**
   * 计算任务进度百分比
   */
  const calculateProgress = (task: CollectionTask): number => {
    const total = task.totalTables
    const completed = task.completedTables + (task.failedTables?.length || 0)
    if (total === 0) return 0
    return Math.round((completed / total) * 100)
  }

  /**
   * 获取进度条状态
   */
  const getProgressStatus = (task: CollectionTask): 'success' | 'exception' | 'active' | 'normal' => {
    if (task.status === TaskStatus.SUCCESS) return 'success'
    if (task.status === TaskStatus.FAILED) return 'exception'
    if (task.status === TaskStatus.RUNNING) return 'active'
    return 'normal'
  }

  const columns: ColumnsType<CollectionTask> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      fixed: 'left',
    },
    {
      title: '数据源',
      dataIndex: 'datasourceName',
      key: 'datasourceName',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (name: string) => (
        <Tooltip placement="topLeft" title={name}>
          {name}
        </Tooltip>
      ),
    },
    {
      title: '采集类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: TaskType) => {
        const config = COLLECTION_TYPE_CONFIG[type]
        return <Tag color={config.color}>{config.text}</Tag>
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: TaskStatus) => {
        const config = STATUS_TAG_CONFIG[status]
        return <Tag color={config.color}>{config.text}</Tag>
      },
    },
    {
      title: '进度',
      key: 'progress',
      width: 250,
      render: (_, task) => {
        const progress = calculateProgress(task)
        const status = getProgressStatus(task)
        return (
          <div>
            <Progress
              percent={progress}
              status={status}
              size="small"
              format={() => `${task.completedTables + (task.failedTables?.length || 0)}/${task.totalTables}`}
            />
            <div className="text-xs text-gray-500 mt-1">
              完成: {task.completedTables} | 失败: {task.failedTables?.length || 0}
            </div>
          </div>
        )
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 180,
      render: (time?: string) => time || '-',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 180,
      render: (time?: string) => time || '-',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, task) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/collections/${task.id}`)}
            >
              详情
            </Button>
          </Tooltip>

          {task.status === TaskStatus.PENDING && (
            <Tooltip title="启动任务">
              <Button
                type="link"
                size="small"
                icon={<PlayCircleOutlined />}
                onClick={() => onStart?.(task.id)}
              >
                启动
              </Button>
            </Tooltip>
          )}

          {task.status === TaskStatus.RUNNING && (
            <Tooltip title="取消任务">
              <Button
                type="link"
                size="small"
                danger
                icon={<PauseCircleOutlined />}
                onClick={() => onCancel?.(task.id)}
              >
                取消
              </Button>
            </Tooltip>
          )}


          {task.status === TaskStatus.FAILED && (
            <Tooltip title="重新执行任务">
              <Button
                type="link"
                size="small"
                icon={<RedoOutlined />}
                onClick={() => onStart?.(task.id)}
              >
                重试
              </Button>
            </Tooltip>
          )}

          {task.status === TaskStatus.PARTIAL_SUCCESS && task.failedTables && task.failedTables.length > 0 && (
            <Tooltip title="重试失败的表">
              <Button
                type="link"
                size="small"
                icon={<RedoOutlined />}
                onClick={() => onRetry?.(task.id)}
              >
                重试
              </Button>
            </Tooltip>
          )}
        </Space>
      ),
    },
  ]

  return (
    <Table<CollectionTask>
      columns={columns}
      dataSource={tasks}
      rowKey="id"
      loading={loading}
      pagination={{
        defaultPageSize: 20,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条`,
      }}
      scroll={{ x: 1200 }}
    />
  )
}

export default CollectionTaskTable
